const bcrypt = require("bcryptjs");
const db = require("../db/index");
const jwt = require("jsonwebtoken");
const { jwtKey } = require("../config");

/** 注册用户 */
const regUser = (req, res) => {
  const userInfo = req.body;

  if (!userInfo.username || !userInfo.password) {
    return res.cc("用户名或密码不能为空");
  }

  const sql = `select * from ev_user where username=?`; // ? 表示占位符

  db.query(sql, [userInfo.username], (err, results) => {
    if (err) return res.cc(err, 500);

    if (results.length > 0) return res.cc("用户名被占用，请更换其他用户名");

    //  用户名可用，插入新用户
    userInfo.password = bcrypt.hashSync(userInfo.password, 10); // 对密码进行加密处理
    db.query(
      `insert into ev_user (username,password) values (?,?)`,
      [userInfo.username, userInfo.password],
      (err, results) => {
        if (err) return res.cc(err, 500);

        if (results.affectedRows !== 1) return res.cc(err);

        return res.send({ status: 200, message: "注册成功" });
      }
    );
  });
};

/** 登录 */
const login = (req, res) => {
  const userInfo = req.body;
  db.query(
    "select * from ev_user where username=?",
    userInfo.username,
    (err, results) => {
      if (err) return res.cc(err, 500);

      if (results.length !== 1) return res.cc("用户名或密码错误"); // 未查询到对应的用户

      const pwd = bcrypt.compareSync(userInfo.password, results[0].password); // 用插件验证密码是否相等

      if (!pwd) return res.cc("用户名或密码错误");

      const user = { ...results[0], password: "", user_pic: "" }; // 剔除密码和头像
      const token = jwt.sign(user, jwtKey, { expiresIn: "12h" }); // 生成token字符串

      res.send({
        status: 200,
        message: "登录成功",
        token: "Bearer " + token,
        userInfo: user,
      });
    }
  );
};

/** 获取用户信息 */
const getUserInfo = (req, res) => {
  db.query(
    "select id,username,nickname,email,user_pick from ev_user where id=?",
    req.auth[0].id,
    (err, results) => {
      if (err) return res.cc(err, 500);

      if (results.length !== 1) return res.cc("获取用户信息失败"); // 未查询到对应的用户

      res.send({
        status: 200,
        message: "获取用户信息成功",
        data: results[0],
      });
    }
  );
};

/** 更新用户信息 */
const updateUserInfo = (req, res) => {
  const userInfo = req.body;

  db.query(
    "update ev_user set nickname=?,email=? where id=?",
    [userInfo.nickname, userInfo.email, userInfo.id],
    (err, results) => {
      if (err) return res.cc(err, 500);

      if (results.affectedRows !== 1) return res.cc("更新用户信息失败"); // 未查询到对应的用户

      res.send({
        status: 200,
        message: "更新用户信息成功",
      });
    }
  );
};

/** 重置密码 */
const resetPwd = (req, res) => {
  db.query(
    "select password from ev_user where id=?",
    req.auth[0].id,
    (err, results) => {
      if (err) return res.cc(err, 500);
      if (results.length !== 1) return res.cc("获取用户信息失败");

      const pwdValidate = bcrypt.compareSync(
        req.body.oldpwd,
        results[0].password
      ); // 用插件验证密码是否相等

      if (!pwdValidate) return res.cc("原密码错误");

      const newPwd = bcrypt.hashSync(req.body.newpwd, 10); // 对密码进行加密处理

      db.query(
        "update ev_user set password=? where id=?",
        [newPwd, req.auth[0].id],
        (err, results) => {
          if (err) return res.cc(err, 500);
          if (results.affectedRows !== 1) return res.cc("更新密码失败");
          res.send({
            status: 200,
            message: "更新密码成功",
          });
        }
      );
    }
  );
};

/** 更新用户头像 */
const updateUserImg = (req, res) => {
  const id = req.auth[0].id;
  const user_pic = req.body.avatar;

  db.query(
    "update ev_user set user_pick=? where id=?",
    [user_pic, id],
    (err, results) => {
      if (err) return res.cc(err, 500);
      if (results.affectedRows !== 1) return res.cc("更新头像失败");
      return res.send({
        status: 200,
        message: "更新头像成功",
      });
    }
  );
};

module.exports = {
  regUser,
  login,
  getUserInfo,
  updateUserInfo,
  resetPwd,
  updateUserImg,
};
